package com.lzx.iteam;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.bean.ChatGroup;
import com.lzx.iteam.bean.CloudContact;
import com.lzx.iteam.bean.ContactNameCard;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.HorizontalTabStrip;
import com.lzx.iteam.widget.WrapContentHeightViewPager;
import io.rong.imkit.RongIM;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Megan on 15/12/29.
 */
public class ContactNameCardActivity extends FragmentActivity implements View.OnClickListener {

    private LinearLayout mLlBack;
    private WrapContentHeightViewPager mVpPager;
    private TextView mTvUserName;
    private TextView mTvHaveNoTeam;
    private ImageView mIvAvatar, mIvSex;
    //    private ImageView mIvStatus;
    private LinearLayout mDefaultNameCard;
    /*private TextView mTvCompany, mTvName, mTvPosition, mTvPhone, mTvEmail, mTvAddress;*/
    private ImageView mIvTalkImage1, mIvTalkImage2, mIvTalkImage3, mIvTalkImage4;
    private HorizontalTabStrip mHtsCategoryStrip;
    private LinearLayout mLlTalkImage;
    private RelativeLayout mRlTalkImage;
    private LinearLayout mLlChatBtn;
    private String mUserId, mUserName, mAvatar, mCompany, mName, mPosition, mPhone, mEmail;
    private int mWhich;
    private StringBuilder mAddress;
    private int mSex;
    private String mLimitPhone;

    private ArrayList<CloudContact> groupInfos = new ArrayList<CloudContact>();
    private ArrayList<String> groups = new ArrayList<String>();

    /*private AllDialogUtil mDialogUtil;
    private SendCardShakeListener mShaker;*/
    private PreferenceUtil mPreferenceUtil;
    private CloudDBOperation mCloudDBOperation;

    private final int GET_CONTACT_NAMECARD = 1000;
    private final int MSG_TALK_PREVIEW = 1001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_CONTACT_NAMECARD:
                    if (msg.arg1 == 0) {
                        ContactNameCard contactNameCard = (ContactNameCard) msg.obj;
                        mUserName = contactNameCard.userName;
                        mAvatar = contactNameCard.avatar;
                        mSex = contactNameCard.sex;
                        groupInfos.addAll(contactNameCard.groups);
                        for (CloudContact group : groupInfos) {
                            groups.add(group.groupName);
                        }
                        mHtsCategoryStrip = (HorizontalTabStrip) ContactNameCardActivity.this.findViewById(R.id.hts_namecard_category_strip);
                        mHtsCategoryStrip.setTabData(groups, ContactNameCardActivity.this);
                        mTvUserName.setText(mUserName);
                        ImageLoaderInterface.imageLoader.displayImage(mAvatar, mIvAvatar, ImageLoaderInterface.optionHeadImage);
                        // 性别
                        if (mSex == 0) {
                            mIvSex.setVisibility(View.GONE);
                        } else if (mSex == 1) {
                            mIvSex.setVisibility(View.VISIBLE);
                            mIvSex.setImageResource(R.drawable.sex_man);
                        } else if (mSex == 2) {
                            mIvSex.setVisibility(View.VISIBLE);
                            mIvSex.setImageResource(R.drawable.sex_lady);
                        }
                        if (groupInfos != null && groupInfos.size() > 0) {
                            /*updataData(0);*/
                            MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
                            mVpPager.setAdapter(adapter);
                            mHtsCategoryStrip.setViewPager(mVpPager);
                            mTvHaveNoTeam.setVisibility(View.GONE);
                            mHtsCategoryStrip.setVisibility(View.VISIBLE);
                            //mDefaultNameCard.setVisibility(View.GONE);
                        } else {
                            mTvHaveNoTeam.setVisibility(View.VISIBLE);
                            mHtsCategoryStrip.setVisibility(View.GONE);
                            //mDefaultNameCard.setVisibility(View.VISIBLE);
//                            mTvName.setText(mUserName);
                        }

                    } else {
                        Toast.makeText(ContactNameCardActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_TALK_PREVIEW:
                    if (msg.arg1 == 0) {
                        ArrayList<String> list = (ArrayList<String>) msg.obj;
                        if (list.size() > 0) {
                            mLlTalkImage.setVisibility(View.VISIBLE);
                            switch (list.size()) {
                                case 4:
                                    ImageLoaderInterface.imageLoader.displayImage(list.get(3), mIvTalkImage4, ImageLoaderInterface.optionEventImage);
                                case 3:
                                    ImageLoaderInterface.imageLoader.displayImage(list.get(2), mIvTalkImage3, ImageLoaderInterface.optionEventImage);
                                case 2:
                                    ImageLoaderInterface.imageLoader.displayImage(list.get(1), mIvTalkImage2, ImageLoaderInterface.optionEventImage);
                                case 1:
                                    ImageLoaderInterface.imageLoader.displayImage(list.get(0), mIvTalkImage1, ImageLoaderInterface.optionEventImage);
                                    break;
                                default:
                                    break;

                            }

                        } else {
                            mLlTalkImage.setVisibility(View.GONE);
                        }
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ContactNameCardActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else if (msg.arg1 == 1002 || msg.arg1 == 1003 || msg.arg1 == 1005) {//其他接口也应该加此判断，当前其他接口未加
                        } else {
                            Toast.makeText(ContactNameCardActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_namecard_layout);
        initView();
        initIntentData();
        initData();
        SealAppContext.getInstance().pushActivity(this);

    }


    private void initView() {
       /* mDialogUtil = AllDialogUtil.getInstance(this);*/
        mCloudDBOperation = new CloudDBOperation(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mLlBack = (LinearLayout) this.findViewById(R.id.ll_contact_namecard_btn_back);
        mTvHaveNoTeam = (TextView) this.findViewById(R.id.tv_contact_namecard_have_no_team);
        mTvUserName = (TextView) this.findViewById(R.id.tv_contact_namecard_username);
        mVpPager = (WrapContentHeightViewPager) this.findViewById(R.id.vp_namecard_viewpager);
        //mDefaultNameCard=(LinearLayout)this.findViewById(R.id.default_namecard);
       /* mTvCompany = (TextView) this.findViewById(R.id.tv_contact_namecard_company);
        mTvName = (TextView) this.findViewById(R.id.tv_contact_namecard_name);
        mTvPosition = (TextView) this.findViewById(R.id.tv_contact_namecard_position);
        mTvPhone = (TextView) this.findViewById(R.id.tv_contact_namecard_phone);
        mTvEmail = (TextView) this.findViewById(R.id.tv_contact_namecard_email);
        mTvAddress = (TextView) this.findViewById(R.id.tv_contact_namecard_address);*/
        mIvAvatar = (ImageView) this.findViewById(R.id.iv_contact_namecard_image);
        mIvSex = (ImageView) this.findViewById(R.id.iv_contact_namecard_sex);
//        mIvStatus=(ImageView)this.findViewById(R.id.iv_contact_namecard_status);
        mIvTalkImage1 = (ImageView) this.findViewById(R.id.iv_contact_namecard_talk_img1);
        mIvTalkImage2 = (ImageView) this.findViewById(R.id.iv_contact_namecard_talk_img2);
        mIvTalkImage3 = (ImageView) this.findViewById(R.id.iv_contact_namecard_talk_img3);
        mIvTalkImage4 = (ImageView) this.findViewById(R.id.iv_contact_namecard_talk_img4);
        mLlTalkImage = (LinearLayout) this.findViewById(R.id.ll_contact_namecard_talk_img);
        mRlTalkImage = (RelativeLayout) this.findViewById(R.id.rl_contact_namecard_talk_img);
        mLlChatBtn = (LinearLayout) this.findViewById(R.id.ll_contact_namecard_chat_btn);

        mLlBack.setOnClickListener(this);
        mRlTalkImage.setOnClickListener(this);
        mIvAvatar.setOnClickListener(this);
        mLlChatBtn.setOnClickListener(this);
    }

    private void initIntentData() {
        Intent intent = getIntent();
        mUserId = intent.getStringExtra("user_id");
    }

    private void initData() {
        getContactNameCard(this, mHandler.obtainMessage(GET_CONTACT_NAMECARD));
        if (!"0".equals(mUserId)) {
            getTalkPreView(this, mHandler.obtainMessage(MSG_TALK_PREVIEW));
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_contact_namecard_btn_back:
                finish();
                break;
         /*   case R.id.tv_contact_namecard_phone:
                if ("1".equals(mLimitPhone)) {
                    showCallDialog();
                } else {
                    Toast.makeText(this, "号码未公开", Toast.LENGTH_LONG).show();
                }

                break;
                */
            case R.id.rl_contact_namecard_talk_img:
                if ("0".equals(mUserId)) {
                    Toast.makeText(this, "对不起，该用户未注册，无法进入其个人空间", Toast.LENGTH_LONG).show();
                } else {
                    Intent intent1 = new Intent(ContactNameCardActivity.this, TalkListActivity.class);
                    intent1.setAction(TalkListActivity.OTHER_PERSONAL_SPACE);
                    intent1.putExtra("set_user_id", mUserId);
                    startActivity(intent1);
                }
                break;

            case R.id.iv_contact_namecard_image:
                ArrayList<String> image = new ArrayList<String>();
                if (mAvatar != null) {
                    image.add(mAvatar.split("\\?")[0]);
                    Intent intent = new Intent(this, ImagePagerActivity.class);
                    intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, image);
                    startActivity(intent);
                }
                break;
            case R.id.ll_contact_namecard_chat_btn:
                if (mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "0").equals(mUserId)) {
                    Toast.makeText(ContactNameCardActivity.this, "对不起，您不能和自己聊天", Toast.LENGTH_LONG).show();
                } else {
                    if ("0".equals(mUserId) || StringUtil.isEmpty(mUserId)) {
                        Toast.makeText(ContactNameCardActivity.this, "该用户尚未注册，请邀请他注册后再发聊天消息", Toast.LENGTH_LONG).show();
                    } else {
                        if (groupInfos.size() > 0) {
/*
                            addChatGroupContact(mUserId, groupInfos.get(mWhich).contactId);
*/
                            RongIM.getInstance().startPrivateChat(ContactNameCardActivity.this, mUserId, mUserName);

                        }
                    }
                }
                break;
        }
    }

    /**
     * 获取用户在多个团队下名片信息
     *
     * @param context
     * @param message
     */
    private void getContactNameCard(Context context, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_USER_ID, mUserId));
        GetContactNameCardMsg getContactNameCardMsg = new GetContactNameCardMsg(context, message);
        getContactNameCardMsg.mApi = AsynHttpClient.API_CONTACT_NAMECARDS;
        getContactNameCardMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execCcHttp(getContactNameCardMsg);
    }

    /**
     * 个人空间预览, 用于联系人详情页
     *
     * @param context
     * @param message
     */
    private void getTalkPreView(Context context, Message message) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TALK_USER_ID, mUserId));
        GetCloudContactTalkPreViewMsg getCloudContactTalkPreViewMsg = new GetCloudContactTalkPreViewMsg(context, message);
        getCloudContactTalkPreViewMsg.mApi = AsynHttpClient.API_TALK_PREVIEW;
        getCloudContactTalkPreViewMsg.mParams = nvps;
        AsynHttpClient.getInstance(context).execTalkHttp(getCloudContactTalkPreViewMsg);
    }


/*
    public void updataData(int position) {
        mWhich=position;
        JSONObject object = groupInfos.get(position).contact_card;
        mPhone = groupInfos.get(position).contact_phone;
        mName = groupInfos.get(position).contactName;
        mLimitPhone = groupInfos.get(position).phone_purview;
        // TODO 此处必须先判断得到数据里有没有公司或者职位的字段
        try {

            if (object != null && object.has("organization")) {
                mCompany = object.getString("organization");
            } else {
                mCompany = "";
            }

            if (object.has("jobtitle")) {

                mPosition = object.getString("jobtitle");
            } else {
                mPosition = "";
            }
            if (object.has("demails")) {

                JSONObject emailObject = object.getJSONObject("demails");
                StringBuilder email = new StringBuilder();
                if (emailObject.has("_$!<Work>!$_")) {
                    email.append(emailObject.getString("_$!<Work>!$_"));
                }
                if (emailObject.has("_$!<Home>!$_")) {
                    email.append("  " + emailObject.getString("_$!<Home>!$_"));
                }
                mEmail = email.toString();

            } else {
                mEmail = "";
            }
*/
/*部门字段目前没了
            if (object.has("department")) {
                mCloudContactDepartment = object.getString("department");
            } else {
                mCloudContactDepartment = "";
            }
*//*


            // 解析地址信息，有两种情况，一种是按原手机通讯录上传格式，一种是后来设置的方式，只有_$!<Work>!$_字段
            mAddress = new StringBuilder();
            if (object.has("daddresses")) {
                JSONObject address = object.getJSONObject("daddresses");
                JSONObject add = address.getJSONObject("_$!<Work>!$_");
                if (add.has("City")) {
                    mAddress.append(add.getString("City"));
                }
                if (add.has("State")) {
                    mAddress.append(add.getString("State"));
                }
                if (add.has("Street")) {
                    mAddress.append(add.getString("Street"));
                }
                if (add.has("ZIP")) {
                    mAddress.append(add.getString("ZIP"));
                }
                if (add.has("Country")) {
                    mAddress.append(add.getString("Country"));
                }

            }
        } catch (JSONException e) {
            try {
                if (object.has("daddresses")) {
                    JSONObject address = object.getJSONObject("daddresses");
                    mAddress.append(address.getString("_$!<Work>!$_"));
                }
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
        Log.i("cloud_contact_data", object.toString());


        // 公司
        if (!StringUtil.isEmpty(mCompany)) {
            mTvCompany.setText(mCompany);
        }
        */
/*部门字段目前没了
        if (!StringUtil.isEmpty(mCloudContactDepartment)) {
            mTvContactDepartment.setVisibility(View.VISIBLE);
            mTvContactDepartment.setText(mCloudContactDepartment);
        } else {
            mTvContactDepartment.setVisibility(View.GONE);
        }
*//*


        // 职位
        if (!StringUtil.isEmpty(mPosition)) {
            mTvPosition.setVisibility(View.VISIBLE);
            mTvPosition.setText(mPosition);
        } else {
            mTvPosition.setText("资料未完善");
        }

        // 邮箱
        if (!StringUtil.isEmpty(mEmail)) {
            mTvEmail.setText(mEmail);
        } else {
            mTvEmail.setText("资料未完善");
        }

        if (!StringUtil.isEmpty(mName)) {
            mTvName.setText(mName);
        } else {
            mTvName.setText("无名称");
        }

        // 办公地址
        if (!StringUtil.isEmpty(mAddress.toString())) {
            mTvAddress.setText(mAddress.toString());
        } else {
            mTvAddress.setText("资料未完善");

        }

       */
/* // 备注
        if (!StringUtil.isEmpty(mCloudContactNote)) {
            mTvContactNote.setText("  " + mCloudContactNote);
        } else {
            mTvContactNote.setText("暂无个人信息");
        }*//*


        // 状态
       */
/* String uid = groupInfos.get(position).userId;
        if (!uid.equals("0")) {
            mIvStatus.setVisibility(View.VISIBLE);
        } else {
            mIvStatus.setVisibility(View.GONE);
        }
*//*

        // 电话
        if ("1".equals(mLimitPhone)) {//显示电话号码
            ArrayList<PhoneNumItem> contactPhoneNum = groupInfos.get(position).contactPhoneNum;
            if (contactPhoneNum != null && contactPhoneNum.size() > 0) {
                Log.i("cloudContact", contactPhoneNum.size() + "");
                // TODO 判断手机号码的个数，一个显示一个，两个以上只显示两个
//            if (contactPhoneNum.size() == 1) {
                mTvPhone.setText(contactPhoneNum.get(0).phoneNum.toString().trim());
                mTvPhone.setTextColor(getResources().getColor(R.color.cloud_contact_detail_blue));
                mTvPhone.setOnClickListener(this);
//            } else if (contactPhoneNum.size() > 1) {
//                mContentLayout.removeAllViews();
//                for (int i = 0; i < 2; i++) {
//                    View cloudPhoneItem = getCloudPhoneItemView(contactPhoneNum.get(i).label, contactPhoneNum.get(i).phoneNum);
//                    mContentLayout.addView(cloudPhoneItem);
//                    mContentLayout.addView(addLine(Constants.dip2px(this, 15)));
//                }
//            }
            }
        } else {
            mTvPhone.setText("限制号码公开");
            mTvPhone.setTextColor(getResources().getColor(R.color.cloud_contact_detail_light));
        }
    }


    private void showCallDialog() {
        mDialogUtil.titleOneDialog(mTvPhone.getText().toString().trim(), "发短信", "打电话");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                CommonCodeUtil.launchSendMessage(ContactNameCardActivity.this, mTvPhone.getText().toString().trim(), null);
                lDialog.dismiss();

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                CommonCodeUtil.launchCallByNumber(ContactNameCardActivity.this, mTvPhone.getText().toString().trim());
                lDialog.dismiss();
            }
        });

    }


    public SendCardShakeListener initShake() {
        SendCardShakeListener shaker = new SendCardShakeListener(this);
        shaker.setOnShakeListener(new SendCardShakeListener.OnShakeListener() {

            public void onShake() {
                if (!StringUtil.isEmpty(mTvPhone.getText().toString().trim())) {
                    if ("1".equals(mLimitPhone)) {
                        CommonCodeUtil.launchCallByNumber(ContactNameCardActivity.this, mTvPhone.getText().toString().trim());
                    } else {
                        Toast.makeText(ContactNameCardActivity.this, "号码未公开", Toast.LENGTH_LONG).show();
                    }

                }
            }
        });
        return shaker;
    }
*/


    public class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return groups.get(position);
        }

        @Override
        public int getCount() {
            return groups.size();
        }

        @Override
        public Fragment getItem(int position) {
            Log.i("ContactNameCardActivity", "--position=" + position + "--groupInfo=" + groupInfos.get(position).toString());
            mWhich = position;
            return ContactNameCardFragment.newInstance(groupInfos.get(position));

        }

    }

}
